ciew = lambda do |env|
  if env['REQUEST_URI'] == '/style.css'
    require 'redcloth'
    require 'sass'
    css = Sass::Engine.new(File.read('style.sass')).render
    return [200, {'Content-Type' => 'text/css'}, [css]]
  else
    require 'cgi'
    require 'fileutils'
    require 'rubygems'
    require 'haml'
    require 'redcloth'
    require 'wiki'

    @Secret = 'hackme'

    wiki = Wiki.new('articles/', 'archive/')
    article = CGI.unescape(env['REQUEST_URI'])
    path = wiki.path(article)

    if File.directory?(path)
      if File.exist?(path + 'index')
        article = article + 'index'
      end
    end

    path = wiki.path(article)

    if env['REQUEST_METHOD'] == 'POST'
      request = Rack::Request.new(env)
      action = request.params['action']
      password = request.params['password']

      if action == 'archive'
        if password == @Secret
          wiki.archive(article)

          return [307, {'Content-Type' => 'text/plain',
          'Location' => File.dirname(article)}, []]
        end
      end
         
      if action == 'save'
        if password == @Secret
          wiki.archive(path)
          wiki.save(article, request.params['text'])
          action = 'view'
        else
          action = 'edit'
        end
      end
    else
      action = 'view'
      action = 'edit' unless File.exist?(path)
    end

    return [200, {'Content-Type' => 'text/html'},
    [Haml::Engine.new(File.read('template.haml')).render(binding())]]
  end
end

apps = []

# you should enable this only if you're hacking on ciew
#apps << Rack::ShowExceptions.new(ciew)

# uncomment either this line or the one above
apps << ciew

run Rack::Cascade.new(apps)
